package com.xinqi.modules.sys.rotation.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.base.response.R;
import com.xinqi.common.base.user.Account;
import com.xinqi.common.core.enums.RotationImageTypeEnum;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.rotation.convert.RotationImageConvert;
import com.xinqi.modules.sys.rotation.domain.RotationImageEntity;
import com.xinqi.modules.sys.rotation.dto.req.RotationImageCreateDTO;
import com.xinqi.modules.sys.rotation.dto.req.RotationImageDeleteDTO;
import com.xinqi.modules.sys.rotation.dto.req.RotationImageEnableDTO;
import com.xinqi.modules.sys.rotation.dto.req.RotationImageQueryDTO;
import com.xinqi.modules.sys.rotation.dto.req.RotationImageUpdateDTO;
import com.xinqi.modules.sys.rotation.dto.rsp.RotationImageResultDTO;
import com.xinqi.modules.sys.rotation.manager.RotationImageManager;
import com.xinqi.modules.sys.rotation.service.RotationImageService;
import com.xinqi.modules.user.user.client.UserClient;
import com.xinqi.modules.user.user.dto.rsp.UserResultDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 系统轮播图服务层实现
 *
 * @author: yyzhenn
 * @date: 2023/04/23
 */
@Validated
@Service("rotationImageService")
@RequiredArgsConstructor
public class RotationImageServiceImpl implements RotationImageService {
    private final RotationImageConvert rotationImageConvert;
    private final RotationImageManager rotationImageManager;

    private final UserClient userClient;

    /**
     * 分页查询 系统轮播图数据
     */
    @Override
    @DS("slaver")
    public PageInfo<RotationImageResultDTO> page(Param pageable, RotationImageQueryDTO query) {
        IPage<RotationImageEntity> page = rotationImageManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, rotationImageConvert::convert);
    }

    /**
     * 查询 PC轮播图数据
     *
     * @Title:
     * @MethodName: listByPc
     * [query]
     * @Return java.util.List<com.xinqi.modules.admin.rotation.dto.rsp.RotationImageResultDTO>
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/4/28 14:24
     */
    @Override
    public List<RotationImageResultDTO> listByPc(Account user, RotationImageQueryDTO query) {
        UserResultDTO result = R.as(userClient.findById(user.getId()));
        if (Objects.nonNull(result)) {
            query.setUserRole(result.getUserRole());
        }
        query.setType(RotationImageTypeEnum.PC.getCode());
        query.setEnableStatus(YesNoNumberEnum.YES.getCode());
        return rotationImageManager.list(wrapper(query)).stream()
            .map(rotationImageConvert::convert).collect(Collectors.toList());
    }

    /**
     * 查询 APP轮播图数据
     *
     * @Title:
     * @MethodName: listByApp
     * [query]
     * @Return java.util.List<com.xinqi.modules.admin.rotation.dto.rsp.RotationImageResultDTO>
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/4/28 14:25
     */
    @Override
    public List<RotationImageResultDTO> listByApp(Account user, RotationImageQueryDTO query) {
        UserResultDTO result = R.as(userClient.findById(user.getId()));
        if (Objects.nonNull(result)) {
            query.setUserRole(result.getUserRole());
        }
        query.setType(RotationImageTypeEnum.APP.getCode());
        query.setEnableStatus(YesNoNumberEnum.YES.getCode());
        return rotationImageManager.list(wrapper(query)).stream()
            .map(rotationImageConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<RotationImageEntity> wrapper(RotationImageQueryDTO query) {
        LambdaQueryWrapper<RotationImageEntity> wrapper = Queries.lambda();
        Queries.accept(query.getType(), v -> wrapper.eq(RotationImageEntity::getType, v));
        Queries.accept(query.getPosition(), v -> wrapper.eq(RotationImageEntity::getPosition, v));
        Queries.accept(query.getUserRole(), v -> wrapper.eq(RotationImageEntity::getUserRole, v));
        Queries.accept(query.getEnableStatus(), v -> wrapper.eq(RotationImageEntity::getEnableStatus, v));
        Queries.accept(query.getName(), v -> wrapper.like(RotationImageEntity::getName, v));
        wrapper.orderByAsc(RotationImageEntity::getSort)
            .orderByDesc(RotationImageEntity::getCreateTime);
        return wrapper;
    }

    /**
     * 根据id查询 系统轮播图数据
     */
    @Override
    public RotationImageResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), MessageUtils.message("rotation.image.id.not.blank"));
        return Optional.ofNullable(rotationImageManager.getById(id)).map(rotationImageConvert::convert).orElse(null);
    }

    /**
     * 新增 系统轮播图数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(RotationImageCreateDTO dto) {
        RotationImageEntity entity = rotationImageConvert.create(dto);
        entity.setReleaseTime(LocalDateTime.now());
        rotationImageManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 系统轮播图数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(RotationImageUpdateDTO dto) {
        Optional.ofNullable(rotationImageManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException(MessageUtils.message("data.does.not.exist")));
        RotationImageEntity entity = rotationImageConvert.update(dto);
        entity.setReleaseTime(LocalDateTime.now());
        return rotationImageManager.updateById(entity);
    }

    /**
     * 禁用/启用
     *
     * @Title:
     * @MethodName: enable
     * [dto]
     * @Return java.lang.Boolean
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/4/28 14:25
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean enable(RotationImageEnableDTO dto) {
        Optional.ofNullable(rotationImageManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException(MessageUtils.message("data.does.not.exist")));
        LambdaUpdateWrapper<RotationImageEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(RotationImageEntity::getEnableStatus, dto.getEnableStatus().getCode())
            .eq(RotationImageEntity::getId, dto.getId());
        return rotationImageManager.update(updateWrapper);
    }

    /**
     * 根据id删除 系统轮播图数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), MessageUtils.message("rotation.image.id.not.blank"));
        return rotationImageManager.removeById(id);
    }

    /**
     * 根据id删除 系统轮播图数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(RotationImageDeleteDTO dto) {
        return deleteById(dto.getId());
    }

}
